package com.test.kotlin.viewmodel

import android.app.Application
import androidx.lifecycle.MutableLiveData

import com.test.kotlin.bean.HomeDataEntity
import com.test.kotlin.bean.HomeNewsEntity
import com.test.kotlin.bean.LinkData
import com.test.kotlin.bean.SpecialTopicEntity
import com.test.kotlin.network.HttpService
import com.test.kotlin.network.NetworkApi
import com.test.library_base.base.BaseViewModel
import com.test.library_base.network.BaseResponse

class MainHomeViewModel(app:Application):BaseViewModel(app){
    var data=MutableLiveData<BaseResponse<HomeDataEntity>>()
    var newsData=MutableLiveData<BaseResponse<HomeNewsEntity>>()
    var specialTopicData=MutableLiveData<BaseResponse<SpecialTopicEntity>>()
    var categoryData=MutableLiveData<MutableList<String>>()
    var linkData=MutableLiveData<MutableList<LinkData>>()

    fun getHomeData():MutableLiveData<BaseResponse<HomeDataEntity>>{
        launchResult({
            NetworkApi.getInstance().create(HttpService::class.java).getHomeData()
        },callback = {
            if(it.isSuccess){
                getLiveNews()
                getSpecialTopic()
                getLevelCategory()
            }
            data.value=it
        })
        return data
    }

    private fun getLiveNews(){
        launchResult({
            NetworkApi.getInstance().create(HttpService::class.java).getLiveNews(pageNumber = 1,pageSize = 4)
        },callback = {
            newsData.value=it
        })
    }

    private fun getSpecialTopic(){
        launchResult({
            NetworkApi.getInstance().create(HttpService::class.java).getSpecialTopic()
        },callback = {
            specialTopicData.value=it
        })
    }

    private fun getLevelCategory(){
        launchResult({
            NetworkApi.getInstance().create(HttpService::class.java).getLevelCategory(name="外部资源")
        },callback = { response ->
            if(response.isSuccess){
                response.data?.let {
                    if(it.get("returnCode").asInt==1){
                        var dataArray=it.get("returnData").asJsonArray
                        if(dataArray!=null&&dataArray.size()>0){
                            var strList= arrayListOf<String>()
                            var size:Int=dataArray.size()
                            dataArray.forEach {obj ->
                                strList.add(obj.asJsonObject.get("categoryName").asString)
                            }
                            categoryData.value=strList
                        }
                    }
                }
            }
        })
    }

    fun getExternalLink(categoryName:String,areaId:String,externalType:String){
        launchResult({
            NetworkApi.getInstance().create(HttpService::class.java).getExternalLink(categoryName=categoryName,areaId =areaId,externalType =externalType )
        },callback = {
            linkData.value=it.data?.returnData as MutableList<LinkData>
        })
    }
}